package com.estore.network;

import com.estore.model.Product;
import com.estore.service.ProductService;

import java.io.*;
import java.net.Socket;
import java.util.*;

import static java.util.Collections.*;

public class EStoreClient {
    // 添加服务器地址和端口号作为成员变量
    private static final String SERVER_ADDRESS = "localhost";
    private static final int SERVER_PORT = 8888;

    // 移除了 ProductService 实例
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    private void showSortedProducts() {
        System.out.println("\n--- 商品列表 (已按价格排序) ---");
        List<Product> products = productService.getAllProducts();
        products.sort((p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()));
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
        } else {
            products.forEach(System.out::println);
        }
    }
    private final ProductService productService = new ProductService();
    public void start() {
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费掉换行符

            switch (choice) {
                // 在退出选项的处理代码中添加
                case 1:
                    browseProducts(null);
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    showSortedProducts();
                    break;
                case 5:
                    productService.saveData(productService.getAllProducts().stream()
                    .collect(java.util.stream.Collectors.toMap(Product::getId, product -> product)));
                    System.out.println("数据已保存，感谢使用！");

                    break;
                case 99: // 隐藏的管理员选项
                    backupData();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n 欢迎来到商城 ");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 添加商品到购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 自定义排序浏览商品");
        System.out.println("5. 退出");
        System.out.print("请输入您的选择: ");
    }

    private void browseProducts(String keyword) {
        Socket socket = null;
        ObjectOutputStream output = null;
        ObjectInputStream input = null;

        try {
            // 创建 Socket 连接到服务器
            socket = new Socket(SERVER_ADDRESS, SERVER_PORT);

            // 获取输入输出流
            output = new ObjectOutputStream(socket.getOutputStream());
            input = new ObjectInputStream(socket.getInputStream());

            // 向服务器发送请求字符串
            output.writeObject("GET_ALL_PRODUCTS");
            output.flush();

            // 从服务器读取响应对象并转换为 List<Product>
            @SuppressWarnings("unchecked")
            List<Product> products = (List<Product>) input.readObject();

            // 打印商品列表到控制台
            System.out.println("\n=== 商品列表 ===");
            if (products.isEmpty()) {
                System.out.println("暂无商品");
            } else {
                System.out.printf("%-5s %-20s %-10s %-10s %-15s%n",
                        "ID", "商品名称", "价格", "库存", "分类");
                System.out.println("----------------------------------------");
                for (Product product : products) {
                    System.out.printf("%-5s %-20s %-10.2f %-10d %-15s%n",
                            product.getId(),
                            product.getName(),
                            product.getPrice(),
                            product.getStock(),
                            product.getCategory());
                }
            }
            System.out.println();

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("与服务器通信时发生错误: " + e.getMessage());
        } finally {
            // 确保资源被正确关闭
            try {
                if (input != null) input.close();
                if (output != null) output.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                System.err.println("关闭连接时发生错误: " + e.getMessage());
            }
        }
    }

    private void sort(List<Product> products) {
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }

    private void backupData() {
        String sourceFile = "products.dat";
        String backupFile = "products.dat.bak";

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupFile)) {

            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int bytesRead;

            // 循环读取和写入数据
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            System.out.println("数据备份成功！备份文件：" + backupFile);

        } catch (Exception e) {
            System.err.println("备份失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new EStoreClient().start();
    }
}